class Manage::UsersController < ApplicationController
  include Security::Session::Access
  include UserData

  def show_my_account
    @user = current_user
    gather_additional_user_info
    render(:partial => "show", :layout => @layout, 
           :locals => {:form_title => "My Account",
                        :update_method => update_method_from(@user.role.id), 
                        :list_method => list_method_from(@user.role.id)})
  end

  def update_my_account
    update_user(current_user.role_id)
  end

  def create_site_admin
    create_user(Role::Id::ADMIN)
  end

  def create_site_user
    create_user(Role::Id::USER)
  end

  def list_site_admins
    @users = User.find(:all, :conditions => ["role_id = 1"],:order => "last_name")
    render(:partial => "list", :layout => @layout , 
           :locals => {:list_title => "Listing admins: ", 
                        :refine_list => "refine_site_admins_list",
                        :role_action => "site_admin"})
  end

  def list_site_users
    @users = user_list(Role::Id::USER)
    render(:partial => "list", :layout => @layout, 
           :locals => {:list_title => "Listing users: ", 
                        :refine_list => "refine_site_users_list",
                        :role_action => "site_user"})
  end

  def refine_site_admins_list
    @users = User.search_for_values(params[:value],Role::Id::ADMIN)
    render(:partial => "list_data", :layout => false,:locals =>{:role_action => "site_admin"})
  end

  def refine_site_users_list
    @users = User.search_for_values(params[:value],Role::Id::USER)
    render(:partial => "list_data", :layout => false,:locals =>{:role_action => "site_user"})
  end

  def show_site_admin
    get_user(Role::Id::ADMIN)
    render(:partial => "show", :layout => @layout, 
           :locals => {:form_title => "Showing Site Admin id: #{@user.id}",
                        :update_method => update_method_from(@user.role.id),
                        :list_method => list_method_from(@user.role.id)})
  end

  def show_site_user
    get_user(Role::Id::USER)
    render(:partial => "show", :layout => @layout, 
           :locals => {:form_title => "Showing user id: #{@user.id}",
                        :update_method => update_method_from(@user.role.id),
                        :list_method => list_method_from(@user.role.id)})
  end

  def update_site_admin
    update_user(Role::Id::ADMIN)
  end


  def update_site_user
    update_user(Role::Id::USER)
  end

  def delete_site_admin
    get_user(Role::Id::ADMIN)
    @user.destroy
    redirect_to(:action => "list_site_admins")
  end

  def delete_site_user
    get_user(Role::Id::USER)
    @user.destroy
    redirect_to(:action => "list_site_users")
  end

  private 
    def user_list(role)
      User.find(:all, :conditions => ["role_id = ?",role],:order => "last_name")
    end

    def update_user(role)
      case request.method
      when :post
        update_user_from_post(role)
        case params[:commit]
        when "Cancel"
          redirect_to(:action => list_method_from(role))
          return
        when "Change Password"
          @user.reset_password = true
        when "Add Address"
          #no special action required. just need to render the form again
          #the update_user_from_post takes care of the address addition
        else
          if save_user?(role)
            flash[:notice] = "User successfully updated"
            redirect_to(:action => show_method_from(role), :id => @user.id)
            return
          end
        end#end case of params[:commit]
      else
        get_user(role)
      end
      render(:partial => "form", :layout => @layout , 
           :locals => {:form_title => form_title(role), 
                        :form_action => form_action(role),
                        :list_method => list_method_from(@user.role.id)})
    end

    def create_user(role)
      case request.method
      when :post
        case params[:commit]
        when "Cancel"
          redirect_to(:action => list_method_from(role))
          return
        else
          create_user_from_post(role)
          if save_user?(role)
            flash[:notice] = "User successfully created"
            redirect_to(:action => show_method_from(role), :id => @user.id)
            return
          else
            @user.reset_password = true
            @user.password = nil
            @user.password_confirmation = nil
          end
        end
      else
        new_user(role)
      end
      render(:partial => "form", :layout => @layout , 
           :locals => {:form_title => form_title(role), 
                        :form_action => form_action(role),
                        :list_method => list_method_from(@user.role.id)})
    end

    def save_user?(role)
      #Errors may have been entered in the additional user information:
      #contacts and addresses
      return if !@user.errors.empty?
      updater = update_updater
      if updater.save
        @user.updater_id = updater.id
        @user.updated_by = current_updater_id
        if @user.save
          if updater.user_id != @user.id
            updater.user_id = @user.id
            updater.save
          end
          update_additional_user_info
          return true
        end
      end
      return false
    rescue Exception => e
      logger.error("Error saving user: #{e}")
      raise
    end

    def update_updater
      updater_name =  @user.first_name + " " + @user.last_name
      return Updater.new(:name => updater_name) unless @user.id

      updater = Updater.find(@user.updater_id)
      updater.name = updater_name
      return  updater
    end

    def new_user(role)
      @user = User.new
      @user.role_id = role
      @user.reset_password = true
      gather_additional_user_info
    end

    def get_user(role)
      @user = User.find(:first, :conditions => ["id = ? and role_id = ?", id_param , role])
      if @user.nil?
        redirect_to(denied_url) 
        return
      end
      gather_additional_user_info
    end

    def create_user_from_post(role)
      @user = User.new
      @user.role_id = role
      @user.reset_password = false
      gather_additional_user_info_from_post
    end

    def update_user_from_post(role)
      @user = User.find(:first, :conditions => ["id = ? and role_id = ?",
                        params[:user][:id].to_i, role])
      if @user.nil?
        redirect_to(denied_url) 
        return
      end
      gather_additional_user_info_from_post
    end

    def show_method_from(role)
      return "show_my_account" if @user && @user.id == current_user_id 
      case role
      when Role::Id::ADMIN
        return "show_site_admin"
      when Role::Id::USER
        return "show_site_user"
      else
        raise "Invalid role"
      end
    end

    def list_method_from(role)
      #return "show_my_account" if @user && @user.id == current_user_id
      case role
      when Role::Id::ADMIN
        return "list_site_admins"
      when Role::Id::USER
        return "list_site_users"
      else
        raise "Invalid role"
      end
    end

    def update_method_from(role)
      case role
      when Role::Id::ADMIN
        return "update_site_admin"
      when Role::Id::USER
        return "update_site_user"
      else
        raise "Invalid role"
      end
    end

    def form_title(role)
      return "My Account" if @user && @user.id == current_user_id
      case role
      when Role::Id::ADMIN
        return "Updating Site Admin id: #{@user.id}" if @user.id
        return "Creating Site Admin"
      when Role::Id::USER
        return "Updating user id: #{@user.id}" if @user.id
        return "Creating user"
      else
        raise "Invalid role"
      end
    end

    def form_action(role)
      #return "update_my_account" if @user && @user.id == current_user_id
      case role
      when Role::Id::ADMIN
        return "update_site_admin" if @user.id
        return "create_site_admin"
      when Role::Id::USER
        if @user.id
          return "update_site_user" 
        end
        return "create_site_user"
      else
        raise "Invalid role"
      end
    end
end
